<template>
  <div class="dept-user-select">
    <div class="dept-list">
      <div class="list-header">
        <span>部门列表</span>
      </div>
      <ul class="filter-list" v-loading="deptLoading">
        <li v-for="dept in deptList" :key="dept.id" class="filter-item" :class="{ active: selectedDeptId === dept.id }">
          <div class="dept-item">
            <el-checkbox :model-value="selectedDepts.includes(dept.id)" @change="(val) => handleDeptSelect(val, dept)" />
            <span class="dept-name" @click="handleDeptClick(dept)">{{ dept.name }}</span>
          </div>
        </li>
      </ul>
    </div>
    <div class="user-list">
      <div class="list-header">
        <span>
          人员列表（部门总人数：
          <span style="color:#f00">{{ userList.length }}</span>，已选：
          <span style="color:#f00">{{ selectedUsers.length }}</span>）
        </span>
        <el-checkbox :model-value="isAllSelected" @change="handleCheckAllChange" :indeterminate="isIndeterminate">全选</el-checkbox>
      </div>
      <ul class="filter-list" v-loading="userLoading">
        <li v-for="user in userList" :key="user.id" class="filter-item">
          <el-checkbox :model-value="selectedUsers.includes(user.id)" @change="(val) => handleUserSelect(val, user)">{{ user.name }}</el-checkbox>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { providerGroupSelectList, providerUserSelectPage } from '@/api/shareFolder'

const props = defineProps({
  modelValue: {
    // 用户ID列表
    type: Array,
    default: () => [],
  },
  groupValue: {
    // 部门ID列表
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:modelValue', 'update:groupValue'])

const deptList = ref([])
const userList = ref([])
const selectedDeptId = ref(null)
const isAllSelected = ref(false)
const isIndeterminate = ref(false)
const selectedUsers = ref([])
const selectedDepts = ref([])
const deptUserMap = ref({})
const deptLoading = ref(false)
const userLoading = ref(false)

// 监听选中用户变化
watch(
  selectedUsers,
  (newVal) => {
    emit('update:modelValue', newVal)
    updateCheckStatus()
    updateDeptStatus()
  },
  { deep: true }
)

// 监听选中部门变化
watch(
  selectedDepts,
  (newVal) => {
    emit('update:groupValue', newVal)
  },
  { deep: true }
)

// 监听外部传入的用户值
watch(
  () => props.modelValue,
  (newVal) => {
    selectedUsers.value = newVal || []
  },
  { deep: true }
)

// 监听外部传入的部门值
watch(
  () => props.groupValue,
  (newVal) => {
    selectedDepts.value = newVal || []
  },
  { deep: true }
)

// 获取部门列表
const getDeptList = async () => {
  try {
    deptLoading.value = true
    const res = await providerGroupSelectList()
    if (res.code === 20000) {
      deptList.value = res.data
      // 如果有选中的部门，只加载选中部门的用户
      if (selectedDepts.value.length > 0) {
        const firstSelectedDept = deptList.value.find((dept) => selectedDepts.value.includes(dept.id))
        if (firstSelectedDept) {
          handleDeptClick(firstSelectedDept)
        }
      }
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  } finally {
    deptLoading.value = false
  }
}

// 获取部门下的用户
const getDeptUsers = async (dept) => {
  return new Promise((resolve, reject) => {
    userLoading.value = true
    providerUserSelectPage({
      groupId: dept.id,
      currentPage: 1,
      pageSize: 99999,
    })
      .then((res) => {
        if (res.code === 20000) {
          // 更新部门用户映射
          deptUserMap.value[dept.id] = res.data.list.map((user) => user.id)
          
          // 如果是当前选中的部门，更新显示的用户列表
          if (selectedDeptId.value === dept.id) {
            userList.value = res.data.list
            updateCheckStatus()
          }
          resolve(res.data.list)
        } else {
          reject(new Error(res.message))
        }
      })
      .catch((error) => {
        console.error('获取部门用户列表失败:', error)
        reject(error)
      })
      .finally(() => {
        userLoading.value = false
      })
  })
}

// 点击部门名称，只显示该部门的用户列表
const handleDeptClick = async (dept) => {
  try {
    selectedDeptId.value = dept.id
    
    // 如果还没有获取过该部门的人员数据，先获取
    if (!deptUserMap.value[dept.id]) {
      await getDeptUsers(dept)
    } else {
      // 如果已经有缓存数据，重新获取以确保数据最新
      const res = await providerUserSelectPage({
        groupId: dept.id,
        currentPage: 1,
        pageSize: 99999,
      })
      
      if (res.code === 20000) {
        deptUserMap.value[dept.id] = res.data.list.map((user) => user.id)
        userList.value = res.data.list
        updateCheckStatus()
      }
    }
  } catch (error) {
    console.error('获取部门用户列表失败:', error)
  }
}

// 更新选择状态
const updateCheckStatus = () => {
  const checkedCount = selectedUsers.value.length
  const totalCount = userList.value.length

  isAllSelected.value = checkedCount === totalCount && totalCount > 0
  isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount
}

// 更新部门选中状态
const updateDeptStatus = () => {
  selectedDepts.value = deptList.value
    .filter((dept) => {
      const deptUsers = deptUserMap.value[dept.id] || []
      return deptUsers.some((userId) => selectedUsers.value.includes(userId))
    })
    .map((dept) => dept.id)
}

// 全选/取消全选当前显示的用户列表
const handleCheckAllChange = (val) => {
  selectedUsers.value = val
    ? [...new Set([...selectedUsers.value, ...userList.value.map((item) => item.id)])]
    : selectedUsers.value.filter((id) => !userList.value.find((user) => user.id === id))
  isIndeterminate.value = false
}

// 选择部门
const handleDeptSelect = async (checked, dept) => {
  try {
    // 如果还没有获取过该部门的人员数据，先获取
    if (!deptUserMap.value[dept.id]) {
      await getDeptUsers(dept)
    }
    
    // 确保已经获取到了人员数据
    const deptUsers = deptUserMap.value[dept.id] || []
    
    if (checked) {
      // 选中部门时，将该部门下所有未选中的用户添加到选中列表
      selectedUsers.value = [...new Set([...selectedUsers.value, ...deptUsers])]
      // 更新部门选中状态
      if (!selectedDepts.value.includes(dept.id)) {
        selectedDepts.value.push(dept.id)
      }
    } else {
      // 取消选中部门时，将该部门下所有用户从选中列表中移除
      selectedUsers.value = selectedUsers.value.filter((id) => !deptUsers.includes(id))
      // 更新部门选中状态
      selectedDepts.value = selectedDepts.value.filter((id) => id !== dept.id)
    }
    
    // 更新全选状态
    updateCheckStatus()
  } catch (error) {
    console.error('处理部门选择失败:', error)
  }
}

// 选择用户时更新部门状态
const handleUserSelect = (checked, user) => {
  if (checked) {
    selectedUsers.value.push(user.id)
  } else {
    selectedUsers.value = selectedUsers.value.filter((id) => id !== user.id)
  }
  updateDeptStatus()
}

onMounted(() => {
  getDeptList()
})
</script>

<style scoped lang="scss">
.dept-user-select {
  display: flex;
  gap: 20px;
  width: 100%;

  .dept-list,
  .user-list {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .list-header {
      padding: 10px;
      border-bottom: 1px solid #dcdfe6;
      font-weight: 500;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .filter-list {
      padding: 0;
      margin: 0;
      max-height: 400px;
      overflow: auto;

      .filter-item {
        padding: 3px 15px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #ecf5ff;
          color: $mainColor;
        }

        .dept-item {
          display: flex;
          gap: 8px;
          :deep(.el-checkbox__label) {
            display: none;
          }
          .dept-name {
            cursor: pointer;
            width: 80%;
          }
        }
      }
    }
  }
}
</style> 